import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects'
import api from '@API'
import { GET_VIDEO_LIST } from '@ACTIONS/video'
import { getVideoList } from './dataSelect'

const getVideoListByTag = function* getVideoListByTag(action) {
  try {
    const { isInitial, tId, queryAssociateTag, tIds } = action
    const list = yield select(getVideoList)
    const params = { tId, skip: isInitial ? 0 : list.length }
    if (queryAssociateTag && tIds) {
      params.tIds = tIds
    }
    let fetchApi = api.getCourses
    if (queryAssociateTag) {
      fetchApi = tIds ? api.getCoursesByTagIds : api.getCoursesByTag
    }
    const { Courses, Total } = yield call(fetchApi, params)
    const newList = isInitial ? Courses : [...list, ...Courses]
    yield put({ type: GET_VIDEO_LIST.SUCCESS, data: newList, total: Total })
  } catch (error) {
    yield put({ type: GET_VIDEO_LIST.FAILURE })
  }
}

export default function* rootSaga() {
  yield all([
    takeLatest(GET_VIDEO_LIST.REQUEST, getVideoListByTag),
  ]);
}

